package com.dd.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dd.reggie.common.R;
import com.dd.reggie.entity.Employee;
import com.dd.reggie.entity.User;
import com.dd.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public R<User> login(HttpServletRequest request, @RequestBody User user){

        log.info(user.toString());

        //根据唯一username查询数据库是否存在该员工
        LambdaQueryWrapper<User> querywrapper = new LambdaQueryWrapper<>();
        querywrapper.eq(User::getPhone, user.getPhone()); //等值查询
        User ump = userService.getOne(querywrapper); //拿到该用户信息

        //3.若不存在该员工返回错误信息
        if(ump == null){
            return R.error("登录失败！");
        }

        //4.若密码不对应则返回错误信息
        if(! ump.getPassword().equals(user.getPassword())){
            return R.error("密码有误，请重新输入！");
        }

        //5.若用户被冻结则返回错误信息
        if(ump.getStatus() == 0) {
            return R.error("您已被冻结！");
        }
        //6.登录成功,并存储ssesion信息
        //在登录成功时，将当前用户数据存到ssesion一份，便于之后获取当前登录对象信息
        request.getSession().setAttribute("user", ump.getId());
        return R.success(ump);
        
    }

}
